package cn.com.sbell.vss.commander;

import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;

import cn.com.sbell.vss.ICommander;
import cn.com.sbell.vss.Response;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.Level;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import cn.com.sbell.vss.VssConstants;
import cn.com.sbell.vss.VssException;

public class SetLoggerLevel implements ICommander{
private static Logger logger=Logger.getLogger(SetLoggerLevel.class);

	public Response execute(HttpServletRequest request) {
		// TODO Auto-generated method stub
		Response response = Response.createResponse(request);
		Document doc = DocumentHelper.createDocument();
		Element root = doc.addElement("parameters");
		String[] strLevel=request.getParameterValues("loggerLevel");
		if(null==strLevel)
		{
			Enumeration e=LogManager.getCurrentLoggers();
			while(e.hasMoreElements()){
				Logger log=(Logger)e.nextElement();
				Element el=root.addElement("logger");
				el.addElement("category").setText(log.getName());
				el.addElement("level").setText(null==log.getLevel()?"":log.getLevel().toString());
				
			}
			response.setParameters(root.asXML());
			return response;
		}
		for (int i = 0; i < strLevel.length; i++) {
			String[] loggerNameValue=strLevel[i].split(",");
			if((null==loggerNameValue)||(loggerNameValue.length<2))
			{
				throw new VssException(VssConstants.CODE_PARAMETER_ERROR);
			}
			Level level=Level.toLevel(loggerNameValue[1], Level.INFO);
			logger.error("Set Logging Level dynamically to:"+loggerNameValue[0]+","+level);
			
			Logger logger=LogManager.getLogger(loggerNameValue[0]);
			if(loggerNameValue[0].equalsIgnoreCase("root"))
			{
				logger=LogManager.getRootLogger();
			}
			logger.setLevel(level);
		}
			
		
		
		
		response.setParameters(root.asXML());
		return response;
	}

}
